<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
    top="2vh">
    <div class="wp-panel">
      <div class="wp-panel__form">
        <el-form :model="productEntryInfo" label-width="120px"  ref="productEntryForm" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="入库单号" prop="stockDetailNo" :rules="[{ required: policy==2, message: '不能为空', trigger: 'blur' }]">
            <el-radio v-model="policy" label="1" border size="mini">自动生成</el-radio>
            <el-radio v-model="policy" label="2" border size="mini">手动输入</el-radio>
            <el-input
              v-if="policy==2"
              class="wp-form-280"
              v-model.trim="productEntryInfo.stockDetailNo"
              placeholder="入库单号"
              clearable
            ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库类型" prop="operationSubType">
                <el-select
                  class="wp-form-280"
                  v-model="productEntryInfo.operationSubType"
                  placeholder="入库类型"
                >
                 <el-option v-for="item in operationSubTypes" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="入库仓库" prop="warehouseCode">
                <Warehouse-search v-model="productEntryInfo.warehouseCode"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item  label="入库时间" prop="stockDate">
                <el-date-picker
                  style="width:280px"
                  v-model="productEntryInfo.stockDate"
                  value-format="yyyy-MM-dd"
                  placeholder="入库时间"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="关联订单号" prop="remark">
                <el-input
                  class="wp-form-280"   :disabled="isDisabled"
                  v-model="productEntryInfo.associateOrder"
                  placeholder="关联订单号"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="wp-panel__talbe">
        <div class="header"  v-if="sourceType=='default'">
          <el-button type="warning" icon="el-icon-plus" @click.native="onOpenPanel">添加产品</el-button>
        </div>
        <el-table
          stripe
          ref="productListTable"
          :data="productList"
          :key="talbekey"
          :row-class-name="tableRowClassName"
          @cell-click="cellclick"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column
            width="120"
            label="产品名称"
            prop="productName"
            show-overflow-tooltip
          ></el-table-column>
        <el-table-column  label="产品类型" prop="productType" show-overflow-tooltip :formatter="formatterProductType"></el-table-column>
          <el-table-column
            label="产品型号"
            prop="productModel"
            show-overflow-tooltip
          ></el-table-column>
          <!-- <el-table-column  width="80" label="产品单位" prop="unit" ></el-table-column> -->
          <el-table-column width="80" v-if="sourceType!=='default'" label="采购数量" prop="purchaseNum"></el-table-column>
          <el-table-column width="100" v-if="sourceType!=='default'" label="已入库数量" prop="storageNum"></el-table-column>
           <el-table-column label="入库价格(元)" :width="sourceType=='default'? 150:100" prop="price">
            <template slot-scope="scope">
              <el-input-number
                v-if="sourceType=='default'"
                size="mini"
                :min="1"
                v-model="scope.row.price"
              ></el-input-number>
              <span v-else>
                {{scope.row.price * (scope.row.discountRate?scope.row.discountRate:1)}}
              </span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="入库数量" prop="productNum">
            <template slot-scope="scope">
              <el-input-number
                v-if="sourceType=='default'"
                size="mini"
                :min="1"
                v-model="scope.row.productNum"
              ></el-input-number>
              <el-input-number
                v-else
                size="mini"
                :min="1"
                :max="scope.row.unStorageNum"
                v-model="scope.row.productNum"
              ></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="备注" show-overflow-tooltip prop="remark">
            <template slot-scope="scope">
              <el-input
                v-if="remarkIsActive(scope.row)"
                maxlength="100"
                size="mini"
                :ref="scope.row.productCode + scope.$index"
                @blur="remarkBlur(scope.row)"
                v-model="scope.row.remark"
              ></el-input>
              <el-tooltip v-else :content="scope.row.remark" placement="top">
                <span>{{ scope.row.remark }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="sourceType=='default'" align="center">
            <template slot-scope="scope">
              <el-link
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="wp-dialog-footer">
      <el-button @click.native="close">取 消</el-button>
      <el-button type="success" @click.native="save('productEntryForm')">确 定</el-button>
    </div>
    <Drawer v-if="sourceType=='default'" ref="entryProductDrawer" width="60%">
      <Product-search
        :plist="productEntryInfo.productList"
        :operationType="1"
        componentName="StockProductCard"
        @save="handleSave"
      ></product-search>
    </Drawer>
  </el-dialog>
</template>
<script>
import Drawer from '@/components/Drawer'
// import ProductSearch from '../ProductSearch'
import ProductSearch from '@/views/eims/components/productSearch/index'
import WarehouseSearch from '@/views/eims/components/WarehouseSeach'
import stock from '@/api/eims/stockAPI'
import Common from '@/views/mixins/common'
export default {
  name: 'ProductEntryPanel',
  components: { Drawer, ProductSearch, WarehouseSearch },
  props: {
    sourceType: {type: String, default: 'default'},
    operationSubTypes: {type: Array,
      default: () => {
        return [
          {value: 10, label: '采购单入库'},
          {value: 13, label: '人工入库'},
          {value: 11, label: '销售退货入库'},
          {value: 12, label: '调拨入库'}
        ]
      }}
  },
  mixins: [Common],
  data () {
    return {
      visible: false,
      title: '',
      talbekey: '',
      policy: '1',
      activeRemarks: [],
      productEntryInfo: {},
      productList: [],
      isDisabled: false,
      rules: {
        operationSubType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        warehouseCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        stockDate: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    reloadList () {
      this.talbekey = Math.random()
    },
    show (title, data) {
      this.visible = true
      this.policy = '1'
      if (data) {
        this.isDisabled = data.associateOrder !== undefined && data.associateOrder !== null
        this.productEntryInfo = { ...data }
        this.productList = this.productEntryInfo.productList ? [...this.productEntryInfo.productList] : []
        this.title = title || '编辑'
      } else {
        this.title = title || '新建'
      }
    },
    save (formName) {
      if (this.checkFormData(formName)) {
        let productList = this.$refs.productListTable.selection
        if (!productList || productList.length <= 0) {
          this.$msgBox.error('请选择入库产品')
          return
        }
        const plist = []
        for (let i = 0; i < productList.length; i++) {
          if (!productList[i].productNum || productList[i].productNum === undefined) {
            this.$msgBox.error('入库数量不能为空')
            return
          }
          const product = {}
          product.productCode = productList[i].productCode
          product.productName = productList[i].productName
          product.productModel = productList[i].productModel
          product.productType = productList[i].productType
          product.unit = productList[i].unit
          product.productNum = productList[i].productNum
          product.purchaseNo = productList[i].purchaseNo
          product.purchaseDetailNo = productList[i].purchaseDetailNo
          product.remark = productList[i].remark
          const discountRate = productList[i].discountRate
          product.price = productList[i].price * (discountRate && discountRate > 0 && discountRate < 1 ? discountRate : 1)
          plist.push(product)
        }
        this.productEntryInfo.operationType = 1
        this.productEntryInfo.productList = plist
        stock.addProductStorageAPI(this.productEntryInfo).then(res => {
          if (res.code === 0) {
            this.close()
            this.$emit('afterSave', res)
          }
        })
      }
    },
    handleSave (data) {
      let productList = this.productEntryInfo.productList || []
      let isSave = true
      if (productList && productList.length > 0) {
        for (let i = 0; i < productList.length; i++) {
          if (data.productCode === productList[i].productCode) {
            productList[i] = { ...data }
            isSave = false
            break
          }
        }
        if (isSave) {
          productList.unshift(data)
        }
      } else {
        productList.unshift(data)
      }
      this.productList = productList
      this.productEntryInfo.productList = productList
      this.reloadList()
    },
    close () {
      this.visible = false
    },
    tooltipRemark (index) {
      return this.activeRemark === index
    },
    dbRemark (index) {
      this.activeRemark = index
    },
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
      return ''
    },
    remarkIsActive (row) {
      return this.activeRemarks.includes(row.productCode)
    },
    remarkBlur (row) {
      this.activeRemarks = this.activeRemarks.filter((item) => {
        return item !== row.productCode
      })
    },
    checkFormData (formName) {
      let f = false
      this.$refs[formName].validate(valid => {
        f = valid
      })
      return f
    },
    cellclick (row, column, cell, event) {
      if (column.property === 'remark') {
        if (!this.activeRemarks.includes(row.productCode)) {
          this.activeRemarks.push(row.productCode)
        }
        this.$nextTick(() => {
          this.$refs[`${row.productCode + row.index}`].focus()
        })
      }
    },
    onOpenPanel () {
      this.$refs.entryProductDrawer.show()
    },
    handleDelete (index, row) {
      this.$msgBox.confirm(
        '确认删除产品' + (row.productName || '') + '?',
        () => {
          this.productEntryInfo.productList.splice(index, 1)
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-panel {
  height: 450px;
  overflow: auto;
  padding: 10px;
}
.wp-panel__talbe {
  text-align: right;
  .header {
    margin-bottom: 5px;
  }
}
</style>
